<template>
  <div class="app-container" v-loading="loading_status" element-loading-text="玩命加载中">
    <div class="search-item">
      <!-- 新增 + 刷新-->
      <el-button
          class="btn" 
          type="primary"
          icon="el-icon-plus"
          size="mini"
          @click="add_dialog = true"
        >新增
        </el-button>
        <el-button @click="reqAllUserList()" class="btn" type="primary" icon="el-icon-refresh" size="mini">
          刷新
        </el-button>
    </div>
      <!-- 表格 -->
    <div class="table-item">
      <el-table
        :data="alluserlist"
        :header-cell-style="{background:'#efefef'}">
        <el-table-column prop="id" label="ID" width="60" sortable />
        <el-table-column prop="name" label="账号" width="180" />
        <el-table-column prop="nickname" label="用户昵称" width="180" />
        <el-table-column prop="created_at" label="创建时间"/>
        <el-table-column prop="updated_at" label="修改时间"/>
        <el-table-column prop="user_pic" label="用户头像" >
          <template slot-scope="scope">
         <img class="user_pic" :src="scope.row.user_pic" alt="">
        </template>
        </el-table-column>
        <el-table-column
          fixed="right"
          label="操作"
          width="100">
          <template slot-scope="scope">
            <el-button @click="modifyUser(scope.row)" type="text" size="small">编辑</el-button>
            <el-button @click="deleteUser(scope.row)" type="text" size="small">删除</el-button>
          </template>
        </el-table-column>
      </el-table>
      <!-- 分页 -->
      <div class="paginat">
        <el-pagination
          background
          layout="total, prev, pager, next"
          :total="alluserlist.length">
        </el-pagination>
      </div>
      <!-- 新增用户 -->
      <el-dialog
        class="add-item"
        title="新增用户"
        width="50%"
        :visible.sync="add_dialog"
        center
        :close="closeAdd">
        <el-form
          ref="addUserFormRef"
          :model="addUserForm"
          :rules="addUserFormRules"
          class="demo-ruleForm"
        >
          <el-form-item label="头像地址：" prop="userpic">
            <div>
                <el-upload
                  :limit="1"
                  class="upload-demo"
                  ref="addupload"
                  :action="aupload_url"
                  :file-list="afileList"
                  :auto-upload="false">
                  <el-button slot="trigger" size="small" type="primary">
                    选择文件
                  </el-button>
                  <div slot="tip" class="el-upload__tip">
                    只能上传jpg/png文件，且不超过500kb
                  </div>
                </el-upload>
            </div>
          </el-form-item>
          <el-form-item label="登录账号：" prop="username">
            <el-input type="text" v-model="addUserForm.username" size="small" placeholder="请输入账号" />
          </el-form-item>
          <el-form-item label="昵称：" prop="nickname">
            <el-input type="text" v-model="addUserForm.nickname" size="small" placeholder="请输入昵称" />
          </el-form-item>
          <el-form-item label="密码：" prop="password">
            <el-input type="password" v-model="addUserForm.password" size="small" placeholder="请输入密码" />
          </el-form-item>
        </el-form>
        <span slot="footer" class="dialog-footer">
          <el-button type="primary" @click="sureAddUser">确 定</el-button>
          <el-button @click="closeAdd">取 消</el-button>
        </span>
      </el-dialog>

      <!-- 编辑用户 -->
     <el-dialog
        class="add-item"
        title="编辑用户"
        width="50%"
        :visible.sync="editVisible"
        center
        close="closeModify">
        <el-form
          ref="addUserFormRef"
          :model="maddUserForm"
          :rules="maddUserFormRules"
          class="demo-ruleForm"
        >
          <el-form-item label="更换头像：" prop="userpic">
            <div>
                <el-upload
                  :limit="1"
                  class="upload-demo"
                  ref="upload"
                  :action="upload_url"
                  :file-list="fileList"
                  :auto-upload="false">
                  <el-button slot="trigger" size="small" type="primary">
                    选择文件
                  </el-button>
                  <div slot="tip" class="el-upload__tip">
                    只能上传jpg/png文件，且不超过500kb
                  </div>
                </el-upload>
            </div>
          </el-form-item>
          <el-form-item label="登录账号：" prop="username">
            <el-input type="text" v-model="maddUserForm.username" size="small" placeholder="请输入账号" />
          </el-form-item>
          <el-form-item label="昵称：" prop="nickname">
            <el-input type="text" v-model="maddUserForm.nickname" size="small" placeholder="请输入昵称" />
          </el-form-item>
          <el-form-item label="密码：" prop="password">
            <el-input type="password" v-model="maddUserForm.password" size="small" placeholder="请输入密码" />
          </el-form-item>
        </el-form>
        <span slot="footer" class="dialog-footer">
          <el-button type="primary" @click="sureModifyUser">确 定</el-button>
          <el-button @click="editVisible = false">取 消</el-button>
        </span>
      </el-dialog>
    </div>
  </div>
</template>

<script>
import { mapState } from 'vuex'

// 引入接口 
import { 
    addUserInfo, 
    deleteUserInfo,
    getAllUserList, 
    modifyUserInfo
} from '@/api/index'

import crypto from 'crypto'
export default {
  name: 'Ruty',
  data() {
    return {
      content: '',
      multipleSelection: [],
      add_dialog: false,
      editVisible: false,
      // 新增
      addUserForm: {
        username: '',
        nickname: '',
        password: '',
      },
      addUserFormRules: {
        username: [
          { required: true, message: '请输入用户名', trigger: 'blur' }
        ],
        nickname: [
          { required: true, message: '请输入邮箱', trigger: 'blur' }
        ],
        password: [
          { required: true, message: '请输入密码', trigger: 'blur' }
        ],
      },
      // 编辑
      maddUserForm: {
        userpic: '',
        username: '',
        nickname: '',
        password: '',
      },
      maddUserFormRules: {
        username: [
          { required: true, message: '请输入用户名', trigger: 'blur' }
        ],
        nickname: [
          { required: true, message: '请输入邮箱', trigger: 'blur' }
        ],
        password: [
          { required: true, message: '请输入密码', trigger: 'blur' }
        ]
      },
      loading_status:false,
      alluserlist:[],
      fileList: [],
      upload_url:'https://vueblog.tiandaodao.com/uploadUserImg',
      aupload_url:'https://vueblog.tiandaodao.com/uploadUserImg',
      afileList: [],
      add_data:{}
    }
  },
  computed: {
  },
  created() {
    this.reqAllUserList()
  },
  mounted() {
  },
  methods: {
    // 获取用户信息
    async reqAllUserList(){
      const _this = this
      _this.loading_status = true
      const res = await getAllUserList();
      if (res.code == 200) {
        _this.alluserlist = res.data 
        _this.loading_status = false
      }else{
        _this.loading_status = false
      }
    },
    // 点击修改用户信息
    modifyUser(row){
      this.editVisible = true
      this.maddUserForm = {
        userpic:row.user_pic,
        username:row.name,
        nickname:row.nickname,
        id:row.id
      }
      this.upload_url = this.upload_url +'?id='+row.id
      // console.log(this.upload_url)
    },
    // 确定修改用户信息
    async sureModifyUser(){
      const _this = this
      if(_this.maddUserForm.password) {
        _this.setMd5()
        const params = {
          id:_this.maddUserForm.id,
          nickname:_this.maddUserForm.nickname,
          name:_this.maddUserForm.username,
          password:_this.maddUserForm.password
        }
        _this.loading_status = true
        const res = await modifyUserInfo(params)
        this.editVisible = false
        if (res.code == 200) {
            this.$message({
              showClose: true,
              message: '修改成功',
              type: 'success'
            });
            // 清空数据
            _this.maddUserForm = {
              userpic:'',
              username:'',
              nickname:'',
              id:''
            }
            
            _this.upload_url = 'https://vueblog.tiandaodao.com/uploadUserImg'
            _this.loading_status = false
            _this.$refs.upload.submit();
            setTimeout((e)=>{
              _this.reqAllUserList()
            },1000)
        }else{  
          _this.loading_status = false
        }
        
      }else{
        this.$message({
          showClose: true,
          message: '请输入密码',
          type: 'error'
        });
      }
    },
    // 修改密码 md5加密
    setMd5(){
      const _this = this
      const md5 = crypto.createHash("md5")
      md5.update(_this.maddUserForm.password)
      _this.maddUserForm.password = md5.digest('hex')
    },
    // 关闭修改时恢复url
    closeModify(){
        this.upload_url = 'https://vueblog.tiandaodao.com/uploadUserImg'
        this.aupload_url = 'https://vueblog.tiandaodao.com/uploadUserImg'
        // 清空数据
        this.addUserForm = {
          password:'',
          username:'',
          nickname:''
        }
    },
    // 关闭新增时恢复url
    closeAdd(){
        this.aupload_url = 'https://vueblog.tiandaodao.com/uploadUserImg'
        // 清空数据
        this.addUserForm = {
          password:'',
          username:'',
          nickname:''
        }
        this.add_dialog = false
    },
    // 点击删除
    deleteUser(row) { 
      const _this = this
      _this.$confirm('确定删除?', '删除提示', {
        cancelButtonText: '取消',
        confirmButtonText: '确定',
        type: 'warning'
      }).then(() => { 
        _this.sureDeleteUser(row)
      }).then(() => {
        
      })
    },
    // 确定删除
    async sureDeleteUser(row){
      const _this = this
      _this.loading_status = true
      const params ={
        id:row.id
      }
      const res = await deleteUserInfo(params)
      if (res.code==200) {
        _this.$message({
          type: 'success',
          message: '删除成功',
          duration: 1000,
        })
        _this.reqAllUserList()
      }
      _this.loading_status = false
    },
    // 添加用户
    async sureAddUser() {
      const _this = this
      if (_this.addUserForm.username&&_this.addUserForm.nickname&&_this.addUserForm.password){
        _this.addSetMd5()//密码加密
        _this.loading_status = true
        const res = await addUserInfo(_this.addUserForm)//新增用户信息
        if (res.code == 200) {
          // console.log(res.insertId)
          if (res.insertId>0) {//新增返回的用户id
            var id = res.insertId
            _this.aupload_url = _this.aupload_url + '?id=' + id
            // 解决 elementui 上传异步找不到id
            setTimeout(function(e){
              _this.$refs.addupload.submit();
              _this.reqAllUserList()
            },1000)
            console.log(_this.aupload_url)
            _this.$message({
              type: 'success',
              message: '添加用户成功！',
              duration:3000
            })
            _this.addUserForm = {}
          }
        }
        _this.add_dialog = false
        _this.loading_status = false
      }else{
        _this.$message.error("请补全信息")
      }
    },
     // 新增密码 md5加密
    addSetMd5(){
      const _this = this
      const md5 = crypto.createHash("md5")
      md5.update(_this.addUserForm.password)
      _this.addUserForm.password = md5.digest('hex')
    },
    // 按钮的启用
    changeSwich(index, row) {
      console.log(row)
    },
    // 搜索
    search() {

    },
    // 编辑-表格内编辑
    modifyClick(){

    }

  }
}
</script>

<style lang="scss" scope>
.app-container{
  .search-item{
    text-align: left;
    height: 70px;
    background-color: #efefef;
    line-height: 70px;
    // padding-left: 20px;
    // display: flex;
    // justify-content: space-between;
    .btn{
      height: 36px;
      margin: 15px 15px;
    }
  }
  .setting-item{
    height: 50px;
    margin-top: 10px;
    background-color: #efefef;
    line-height: 50px;
    padding-left: 10px;
    display: flex;
    justify-content: space-between;
    .link-item{
      margin: 0 30px;
      i{
        font-size: 20px;
        padding-right: 5px;
      }
    }
  }
  .table-item{
    border: 1px solid #e6e6e6;
    .add-item{
      width: 85%;
    }
    .input{
      padding-right: 200px;
    }
  }
  .el-table__header .el-table-column--selection .cell{
    margin-left: 4px;
}
.el-pagination{
  text-align: start;
}

}
.user_pic{
  width: 40px;
  height: 40px;
  box-shadow: 0 0 10px #aaa;
}
.user_header{
  width: 40px;
  height: 40px;
  box-shadow: 0 0 10px #aaa;
}
.paginat{
  text-align:right;
  padding:10px;
}
.app-container .el-pagination{
  text-align:right;
}
</style>
